package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.ProjectDevice;
import com.sskj.api.exception.LogicException;
import com.sskj.api.mapper.ProjectDeviceMapper;
import com.sskj.api.service.IProjectDeviceService;
import com.sskj.api.vo.req.ProjectDevicePageListReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

@Slf4j
@Service
public class ProjectDeviceService extends ServiceImpl<ProjectDeviceMapper, ProjectDevice> implements IProjectDeviceService {

    @Override
    public void add(ProjectDevice projectDevice) {
        LambdaQueryWrapper<ProjectDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProjectDevice::getDeviceId, projectDevice.getDeviceId());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("设备已绑定其他项目");
        }

        projectDevice.setCreateTime(LocalDateTime.now());
        save(projectDevice);
    }

    @Override
    public void deleteById(Long id) {
        removeById(id);
    }

    @Override
    public void update(Long projectId, Long deviceId) {
        LambdaQueryWrapper<ProjectDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProjectDevice::getDeviceId, deviceId);
        remove(lambdaQueryWrapper);

        ProjectDevice projectDevice = new ProjectDevice();
        projectDevice.setProjectId(projectId);
        projectDevice.setDeviceId(deviceId);
        projectDevice.setCreateTime(LocalDateTime.now());
        save(projectDevice);
    }

    @Override
    public void deleteByProjectId(Long projectId) {
        LambdaQueryWrapper<ProjectDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProjectDevice::getProjectId, projectId);
        remove(lambdaQueryWrapper);
    }

    @Override
    public void deleteByDeviceId(Long deviceId) {
        LambdaQueryWrapper<ProjectDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProjectDevice::getDeviceId, deviceId);
        remove(lambdaQueryWrapper);
    }

    @Override
    public IPage<ProjectDevice> pageList(ProjectDevicePageListReq req) {
        IPage<ProjectDevice> page = new Page<>(req.getPageNum(), req.getPageSize());
        return baseMapper.pageList(page, req);
    }

    @Override
    public Long countDevices(Long projectId) {
        LambdaQueryWrapper<ProjectDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProjectDevice::getProjectId, projectId);
        return count(lambdaQueryWrapper);
    }
}
